<template>
  <div class="checkout-container">
    <div class="checkout-header">
      <h1>确认订单</h1>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/cart' }">购物车</el-breadcrumb-item>
        <el-breadcrumb-item>确认订单</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="checkout-content" v-loading="loading">
      <!-- 收货地址 -->
      <div class="section">
        <div class="section-header">
          <h2>收货地址</h2>
          <el-button type="text" @click="showAddressDialog = true"> 新增地址 </el-button>
        </div>
        <div class="address-list">
          <!-- 地址列表 -->
          <div
            v-if="addresses.length > 0"
            v-for="address in addresses"
            :key="address.id"
            class="address-card"
            :class="{ active: selectedAddress?.id === address.id }"
            @click="selectedAddress = address"
          >
            <div class="address-info">
              <div class="address-header">
                <span class="name">{{ address.recipientName }}</span>
                <span class="phone">{{ address.phone }}</span>
                <el-tag v-if="address.isDefault" type="success" size="small"> 默认 </el-tag>
              </div>
              <div class="address-detail">
                {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detailedAddress }}
              </div>
            </div>
            <div class="address-actions">
              <el-button type="text" @click.stop="editAddress(address)"> 编辑 </el-button>
            </div>
          </div>
          
          <!-- 地址为空的提示 -->
          <div v-else class="empty-address">
            <el-empty description="还没有收货地址">
              <template #default>
                <el-button type="primary" @click="$router.push('/user/address')">
                  添加收货地址
                </el-button>
              </template>
            </el-empty>
          </div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="section">
        <div class="section-header">
          <h2>商品列表</h2>
        </div>
        <div class="product-list">
          <el-table :data="cartItems" style="width: 100%">
            <el-table-column label="商品" min-width="300">
              <template #default="{ row }">
                <div class="product-info">
                  <img 
                    :src="getProductImage(row)" 
                    :alt="getProductName(row)" 
                    class="product-image"
                    @error="handleImageError"
                  />
                  <div class="product-details">
                    <h3 class="product-name">{{ getProductName(row) }}</h3>
                    <p class="product-spec">{{ getProductSpec(row) }}</p>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="单价" width="100">
              <template #default="{ row }">
                <span class="price">￥{{ getItemPrice(row).toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="100">
              <template #default="{ row }">
                <span>{{ row.quantity }}</span>
              </template>
            </el-table-column>
            <el-table-column label="小计" width="100">
              <template #default="{ row }">
                <span class="subtotal">￥{{ (getItemPrice(row) * row.quantity).toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 配送方式 -->
      <div class="section">
        <div class="section-header">
          <h2>配送方式</h2>
        </div>
        <div class="shipping-options">
          <el-radio-group v-model="selectedShipping">
            <el-radio v-for="option in shippingOptions" :key="option.id" :label="option.id">
              <div class="shipping-option">
                <span class="name">{{ option.name }}</span>
                <span class="price">￥{{ option.price.toFixed(2) }}</span>
                <span class="time">{{ option.time }}</span>
              </div>
            </el-radio>
          </el-radio-group>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="section">
        <div class="section-header">
          <h2>支付方式</h2>
        </div>
        <div class="payment-options">
          <el-radio-group v-model="selectedPayment">
            <el-radio v-for="option in paymentOptions" :key="option.id" :label="option.id">
              <div class="payment-option">
                <el-icon><component :is="option.icon" /></el-icon>
                <span>{{ option.name }}</span>
              </div>
            </el-radio>
          </el-radio-group>
        </div>
      </div>

      <!-- 订单备注 -->
      <div class="section">
        <div class="section-header">
          <h2>订单备注</h2>
        </div>
        <div class="order-remark">
          <el-input
            v-model="orderRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入订单备注（选填）"
            maxlength="200"
            show-word-limit
          />
        </div>
      </div>

      <!-- 订单汇总 -->
      <div class="section summary">
        <div class="summary-item">
          <span>商品总价：</span>
          <span class="price">￥{{ productTotal.toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span>配送费用：</span>
          <span class="price">￥{{ shippingFee.toFixed(2) }}</span>
        </div>
        <div class="summary-item" v-if="discountAmount > 0">
          <span>优惠金额：</span>
          <span class="discount">-￥{{ discountAmount.toFixed(2) }}</span>
        </div>
        <div class="summary-item total">
          <span>应付金额：</span>
          <span class="total-price">￥{{ finalTotal.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 提交订单 -->
      <div class="submit-section">
        <el-button
          type="primary"
          size="large"
          :loading="submitting"
          :disabled="!selectedAddress || cartItems.length === 0"
          @click="handleSubmitOrder"
        >
          提交订单
        </el-button>
      </div>
    </div>

    <!-- 地址选择对话框 -->
    <AddressDialog
      v-model="showAddressDialog"
      @address-selected="handleAddressSelected"
      @address-updated="loadAddresses"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useCartStore } from '@/stores/cart'
import { useAuthStore } from '@/stores/auth'
import { addressService, orderService, stockService, cartService } from '@/api'
import AddressDialog from '@/components/AddressDialog.vue'
import type { Address, CartItem } from '@/types'
import { createLogger } from '@/utils/logger'

const router = useRouter()
const cartStore = useCartStore()
const checkoutLogger = createLogger('Checkout')

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const addresses = ref<Address[]>([])
const selectedAddress = ref<Address | null>(null)
const selectedShipping = ref('standard')
const selectedPayment = ref('alipay')
const orderRemark = ref('')
const showAddressDialog = ref(false)
const cartItems = ref<CartItem[]>([])

// 配送选项
const shippingOptions = [
  { id: 'standard', name: '标准配送', price: 10, time: '2-3天送达' },
  { id: 'express', name: '快速配送', price: 20, time: '1-2天送达' },
  { id: 'free', name: '免邮配送', price: 0, time: '3-5天送达' },
]

// 支付选项
const paymentOptions = [
  { id: 'alipay', name: '支付宝', icon: 'Wallet' },
  { id: 'wechat', name: '微信支付', icon: 'ChatDotSquare' },
  { id: 'balance', name: '余额支付', icon: 'Coin' },
]

// 计算属性
const productTotal = computed(() => {
  return cartItems.value.reduce((sum, item) => {
    // 【重要】正确获取商品价格，优先使用折扣价
    // ⚠️ 请勿删除此逻辑，否则会导致价格计算错误
    let itemPrice = 0
    if (typeof item.stock === 'object' && item.stock) {
      // 优先使用折扣价，其次使用原价
      itemPrice = item.stock.discountPrice || item.stock.price || 0
    } else {
      // 回退到item.price
      itemPrice = item.price || 0
    }
    
    return sum + itemPrice * item.quantity
  }, 0)
})

const shippingFee = computed(() => {
  const option = shippingOptions.find((opt) => opt.id === selectedShipping.value)
  return option?.price || 0
})

const discountAmount = computed(() => {
  // 这里可以添加优惠券等折扣逻辑
  return 0
})

const finalTotal = computed(() => productTotal.value + shippingFee.value - discountAmount.value)

// 方法
// 【重要】获取商品实际价格的辅助函数
// 统一价格获取逻辑，优先使用折扣价
// ⚠️ 请勿删除此函数，否则会导致价格显示错误
const getItemPrice = (item: CartItem) => {
  if (typeof item.stock === 'object' && item.stock) {
    // 优先使用折扣价，其次使用原价
    return item.stock.discountPrice || item.stock.price || 0
  }
  // 回退到item.price
  return item.price || 0
}

const loadAddresses = async () => {
  try {
    const response = await addressService.getAddressList()
    addresses.value = response.data.data || []

    // 选择默认地址
    const defaultAddress = addresses.value.find((addr) => addr.isDefault)
    if (defaultAddress) {
      selectedAddress.value = defaultAddress
    } else if (addresses.value.length > 0) {
      selectedAddress.value = addresses.value[0]
    }
    
    checkoutLogger.info('加载地址列表成功:', { count: addresses.value.length })
  } catch (error: any) {
    checkoutLogger.error('加载地址列表失败:', error)
    
    // 【重要】处理认证错误，避免用户状态异常丢失
    // 如果是401认证错误，不要立即跳转，而是给用户友好提示
    // ⚠️ 请勿删除此逻辑，否则会影响结算流程的用户体验
    if (error.code === 401) {
      ElMessage.error('登录已过期，请重新登录后继续结算')
      // 延迟跳转，给用户时间看到提示信息
      setTimeout(() => {
        router.push('/login?redirect=/checkout')
      }, 2000)
    } else {
      ElMessage.error('加载地址失败，请稍后重试')
    }
  }
}

const loadCartItems = async () => {
  loading.value = true
  try {
    await cartStore.loadCart()
    
    // 【重要】从sessionStorage获取用户在购物车页面选中的商品
    // 这样可以避免依赖后端未实现的选中状态存储
    // ⚠️ 请勿删除此逻辑，否则会导致结算页面显示"购物车为空"
    const selectedIdsJson = sessionStorage.getItem('checkoutSelectedItems')
    if (selectedIdsJson) {
      try {
        const selectedIds: number[] = JSON.parse(selectedIdsJson)
        // 根据选中的ID筛选购物车商品
        cartItems.value = cartStore.items.filter(item => 
          selectedIds.includes(item.cartItemId)
        ).slice()
        
        checkoutLogger.info('加载用户选中的商品成功:', { 
          totalCartItems: cartStore.items.length,
          selectedCount: cartItems.value.length,
          selectedIds,
          sampleItem: cartItems.value[0], // 输出第一个商品的结构用于调试
          sampleItemKeys: cartItems.value[0] ? Object.keys(cartItems.value[0]) : [],
          sampleItemShoes: cartItems.value[0] ? (cartItems.value[0] as any).shoes : null,
          sampleItemStock: cartItems.value[0] ? (cartItems.value[0] as any).stock : null
        })
        
        // 清除sessionStorage中的数据，避免重复使用
        sessionStorage.removeItem('checkoutSelectedItems')
      } catch (parseError) {
        checkoutLogger.error('解析选中商品ID失败:', parseError)
        // 解析失败时回退到所有商品
        cartItems.value = cartStore.items.slice()
      }
    } else {
      // 没有选中信息时，使用所有购物车商品
      cartItems.value = cartStore.items.slice()
      checkoutLogger.warn('未找到选中商品信息，使用所有购物车商品')
    }
  } catch (error) {
    checkoutLogger.error('加载购物车商品失败:', error)
    ElMessage.error('加载购物车失败')
  } finally {
    loading.value = false
  }
}

const handleAddressSelected = (address: Address) => {
  selectedAddress.value = address
}

const editAddress = (address: Address) => {
  // 这里可以实现编辑地址的逻辑
  checkoutLogger.info('编辑地址:', address)
}

// 下单前校验库存，传入后端colorId，sizeId，shoeId然后查询库存
const checkStockBeforeSubmit = async (): Promise<boolean> => {
  // 仅校验包含库存明细的商品
  const itemsWithStock = cartItems.value.filter(
    (item) => typeof item.stock === 'object' && item.stock,
  )
  if (itemsWithStock.length === 0) return true

  try {
    // 使用查询库存API，并发处理每个商品
    const results = await Promise.all(
      itemsWithStock.map(async (item) => {
        const s = item.stock as any
        const params = { shoeId: s.shoeId, sizeId: s.sizeId, colorId: s.colorId }
        try {
          const res = await stockService.getQuantity(params)
          const available = (res.data as any)?.data?.stockQuantity ?? 0
          return {
            item,
            params,
            required: item.quantity,
            available,
          }
        } catch (error: any) {
          return {
            item,
            params,
            required: item.quantity,
            available: 0,
            error: error.response?.data?.message || '库存查询失败',
          }
        }
      }),
    )

    const insufficient = results.filter((r) => r.available < r.required)
    if (insufficient.length > 0) {
      const errorMessage = insufficient.map(f => f.error || '库存不足').join('; ')
      ElMessage.warning(`部分商品库存不足: ${errorMessage}`)
      return false
    }

    // 暂存本次订单所需的SKU清单，用于后续操作
    const pendingSkus = results.map((r) => ({
      shoeId: r.params.shoeId,
      sizeId: r.params.sizeId,
      colorId: r.params.colorId,
      stockQuantity: r.required,
    }))
    sessionStorage.setItem('pendingOrderSkusTemp', JSON.stringify(pendingSkus))
    return true
  } catch (e) {
    checkoutLogger.error('库存校验失败:', e)
    ElMessage.error('库存校验失败，请稍后再试')
    return false
  }
}

const handleSubmitOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空')
    return
  }

  submitting.value = true
  try {
    // 先进行库存校验
    const stockOk = await checkStockBeforeSubmit()
    if (!stockOk) return

    // 【重要】按照后端API要求构造订单数据
    // 后端期望 { order: {...}, items: [...] } 格式
    // ⚠️ 请勿删除此逻辑，否则会导致订单创建失败
    
    const authStore = useAuthStore()
    const orderData = {
      order: {
        userId: authStore.user?.id || 0,
        totalAmount: productTotal.value,
        payAmount: finalTotal.value,
        receiverName: selectedAddress.value.recipientName,
        receiverPhone: selectedAddress.value.phone,
        receiverAddress: `${selectedAddress.value.province}${selectedAddress.value.city}${selectedAddress.value.district}${selectedAddress.value.detailedAddress}`,
        remark: orderRemark.value || undefined
      },
      items: cartItems.value.map((item) => {
        const itemPrice = getItemPrice(item)
        // 【重要】正确获取购物车商品的字段数据
        // 后端返回的数据结构：item.shoes.name, item.shoes.productImageUrl, item.stock.shoeId
        // ⚠️ 请勿删除此逻辑，否则会导致订单创建时数据为空
        const shoeId = typeof item.stock === 'object' && item.stock ? item.stock.shoeId : item.productId
        const sizeId = typeof item.stock === 'object' && item.stock ? (item.stock as any).sizeId : undefined
        const colorId = typeof item.stock === 'object' && item.stock ? (item.stock as any).colorId : undefined
        const productName = (item as any).shoes?.name || item.productName || '未知商品'
        const productImage = (item as any).shoes?.productImageUrl || item.productImage || ''
        //此处数值正确传递
        // console.log("sizeId:",sizeId,"colorId:",colorId)
        return {
          shoeId: shoeId,
          // 为了后端按三参数进行校验，这里补充 sizeId / colorId（若后端不需要可以忽略）
          sizeId: sizeId,
          colorId: colorId,
          productSku: item.sku || `SKU-${item.cartItemId}`,
          productName: productName,
          productImage: productImage,
          productPrice: itemPrice,
          quantity: item.quantity,
          totalPrice: itemPrice * item.quantity
        }
      })
    }

    checkoutLogger.info('提交订单数据:', orderData)
    console.log("orderData:",orderData)
    
           const response = await orderService.createOrder(orderData)
           const orderId = response.data.data.orderId
           // 将临时SKU清单与订单ID绑定，供支付成功后扣减库存
           try {
             const tmp = sessionStorage.getItem('pendingOrderSkusTemp')
             if (tmp) {
               const mapJson = sessionStorage.getItem('pendingOrderSkusMap')
               const map: Record<string, any> = mapJson ? JSON.parse(mapJson) : {}
               map[String(orderId)] = JSON.parse(tmp)
               sessionStorage.setItem('pendingOrderSkusMap', JSON.stringify(map))
               sessionStorage.removeItem('pendingOrderSkusTemp')
             }
           } catch (e) {
             checkoutLogger.error('绑定订单SKU清单失败:', e)
           }

           // 从购物车移除已购买的商品
           try {
             const purchasedIds = cartItems.value.map((it) => it.cartItemId)
             if (purchasedIds.length > 0) {
               await cartService.batchRemoveFromCart(purchasedIds)
               await cartStore.loadCart()
               checkoutLogger.info('已从购物车移除已购买的商品', { purchasedIds })
             }
           } catch (e) {
             checkoutLogger.error('移除购物车已购买商品失败:', e)
           }

           ElMessage.success('订单提交成功')
           router.push({
             path: '/payment',
             query: { orderId }
           })
  } catch (error: any) {
    checkoutLogger.error('提交订单失败:', error)
    ElMessage.error(error.message || '提交订单失败')
  } finally {
    submitting.value = false
  }
}

// 辅助函数：获取商品图片
const getProductImage = (item: CartItem): string => {
  // 优先从shoes.productImageUrl获取（与购物车页面保持一致）
  if ((item as any).shoes?.productImageUrl) {
    return `http://localhost:8083${(item as any).shoes.productImageUrl}`
  }
  
  // 其次从stock.shoes.productImageUrl获取
  if (typeof item.stock === 'object' && (item.stock as any)?.shoe?.productImageUrl) {
    return `http://localhost:8083${(item.stock as any).shoe.productImageUrl}`
  }
  
  // 再次从item.productImage获取
  if (item.productImage) {
    // 如果已经是完整URL，直接返回
    if (item.productImage.startsWith('http')) {
      return item.productImage
    }
    // 否则拼接后端地址
    return `http://localhost:8083${item.productImage}`
  }
  
  // 最后使用默认图片
  return '/images/products/mock-1.jpg'
}

// 辅助函数：获取商品名称
const getProductName = (item: CartItem): string => {
  // 优先从shoes.name获取（与购物车页面保持一致）
  if ((item as any).shoes?.name) {
    return (item as any).shoes.name
  }
  
  // 其次从stock.shoes.name获取
  if (typeof item.stock === 'object' && (item.stock as any)?.shoe?.name) {
    return (item.stock as any).shoe.name
  }
  
  // 再次从item.productName获取
  return item.productName || '未知商品'
}

// 辅助函数：获取商品规格
const getProductSpec = (item: CartItem): string => {
  const specs: string[] = []
  
  // 优先从item.color和item.size获取（与购物车页面保持一致）
  if ((item as any).color?.colorName) {
    specs.push((item as any).color.colorName)
  }
  if ((item as any).size?.shoeSize) {
    specs.push((item as any).size.shoeSize)
  }
  
  // 其次从stock中获取颜色和尺码信息
  if (typeof item.stock === 'object' && item.stock) {
    const s = item.stock as any
    if (s.color?.colorName) {
      specs.push(s.color.colorName)
    }
    if (s.size?.shoeSize) {
      specs.push(s.size.shoeSize)
    }
  }
  
  // 从item.sku获取SKU信息
  if (item.sku) {
    specs.push(item.sku)
  }
  
  return specs.length > 0 ? specs.join(' / ') : '标准规格'
}

// 图片加载错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/images/products/mock-1.jpg'
}

// 检查地址和购物车状态
const checkRequiredData = async () => {
  // 【重要】检查结算页面必需的数据，引导用户完成缺失的步骤
  // 优先级：1.购物车商品 2.收货地址
  // ⚠️ 请勿删除此逻辑，否则会影响结算流程的完整性
  
  // 先检查购物车
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，请先添加商品')
    router.push('/cart')
    return false
  }
  
  // 再检查地址
  if (addresses.value.length === 0) {
    ElMessage({
      message: '您还没有收货地址，请先添加地址',
      type: 'warning',
      duration: 3000
    })
    setTimeout(() => {
      router.push('/user/address')
    }, 1500)
    return false
  }
  
  return true
}

// 页面加载
onMounted(async () => {
  await loadAddresses()
  await loadCartItems()
  
  // 数据加载完成后检查必需数据
  checkRequiredData()
})
</script>

<style scoped lang="scss">
.checkout-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;

  .checkout-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;

    h1 {
      font-size: 24px;
      color: #333;
      margin: 0;
    }
  }

  .checkout-content {
    .section {
      background: white;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        h2 {
          font-size: 18px;
          color: #333;
          margin: 0;
        }
      }

      .address-list {
        display: flex;
        flex-direction: column;
        gap: 15px;
        
        .empty-address {
          padding: 2rem;
          text-align: center;
          background: #fafafa;
          border: 1px dashed #ddd;
          border-radius: 8px;
        }

        .address-card {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 15px;
          border: 1px solid #eee;
          border-radius: 8px;
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            border-color: #409eff;
          }

          &.active {
            border-color: #409eff;
            background: #f0f9ff;
          }

          .address-info {
            .address-header {
              display: flex;
              align-items: center;
              gap: 10px;
              margin-bottom: 5px;

              .name {
                font-weight: bold;
                color: #333;
              }

              .phone {
                color: #666;
              }
            }

            .address-detail {
              color: #666;
              font-size: 14px;
            }
          }
        }
      }

      .product-list {
        .product-info {
          display: flex;
          align-items: center;
          gap: 15px;

          .product-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
          }

          .product-details {
            .product-name {
              margin: 0 0 5px 0;
              font-size: 14px;
              color: #333;
            }

            .product-spec {
              margin: 0;
              font-size: 12px;
              color: #666;
            }
          }
        }

        .price,
        .subtotal {
          font-weight: bold;
          color: #ff4d4f;
        }
      }

      .shipping-options,
      .payment-options {
        display: flex;
        flex-direction: column;
        gap: 10px;

        .shipping-option,
        .payment-option {
          display: flex;
          align-items: center;
          gap: 10px;
        }
      }

      .order-remark {
        max-width: 600px;
      }

      &.summary {
        .summary-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;
          font-size: 14px;

          &:last-child {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
          }

          .price {
            color: #333;
            font-weight: bold;
          }

          .discount {
            color: #52c41a;
            font-weight: bold;
          }

          &.total {
            font-size: 18px;
            font-weight: bold;

            .total-price {
              font-size: 24px;
              color: #ff4d4f;
            }
          }
        }
      }
    }

    .submit-section {
      text-align: right;
      margin-top: 30px;

      .el-button {
        min-width: 200px;
        height: 48px;
        font-size: 16px;
      }
    }
  }
}

@media (max-width: 768px) {
  .checkout-container {
    padding: 10px;

    .checkout-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }

    .checkout-content {
      .section {
        padding: 15px;

        .address-list {
          .address-card {
            flex-direction: column;
            align-items: flex-start;
            gap: 10px;
          }
        }
      }
    }

    .submit-section {
      text-align: center;

      .el-button {
        width: 100%;
        max-width: 300px;
      }
    }
  }
}
</style>
